package com.kfm.wiki.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.crypto.digest.MD5;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kfm.wiki.entity.User;
import com.kfm.wiki.ex.BussinessException;
import com.kfm.wiki.mapper.UserMapper;
import com.kfm.wiki.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.util.List;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageInfo<User> list(Integer current, Integer pageSize, User user) {
        PageHelper.startPage(current, pageSize);
        List<User> users = userMapper.selectList(user);
        return new PageInfo<>(users);
    }

    @Override
    public void save(User user) {
        if (ObjectUtils.isEmpty(user.getId())){
            // 新增
            user.setId(IdUtil.getSnowflakeNextId());

            // 密码加密
            user.setPassword(MD5.create().digestHex(user.getPassword()));

            // 先判断是否存在，再插入
            if (hasLoginName(user.getLoginName())){
                throw new BussinessException("用户名已存在");
            }
            userMapper.insert(user);
        } else{
            if (StringUtils.hasLength(user.getPassword())){
                user.setPassword(MD5.create().digestHex(user.getPassword()));
            }
            userMapper.updateById(user);
        }
    }

    @Override
    public void removeById(Long id) {
        userMapper.deleteById(id);
    }

    @Override
    public User login(User user) {
        user.setPassword(MD5.create().digestHex(user.getPassword()));
        List<User> users = userMapper.selectList(user);

        if (users.size() == 1){
            return users.get(0);
        } else {
            throw new BussinessException("用户名或密码错误");
        }
    }

    private boolean hasLoginName(String loginName){
        User user = new User();
        user.setLoginName(loginName);

        return userMapper.selectList(user).size() > 0;
    }
}
